<template>
  <div :class="{border: isBorder}" class="address">
    <template>
      <select
        :style="{width: `${31}%`}"
        @change="getCities"
        v-model="currentProvince"
        :disabled="disabled"
        :class="{'area-block': isBlock}">
        <option :value="placeholders.province">{{ placeholders.province }}</option>
        <option v-for="(item, index) in provinces" :value="item" :title="item">{{ item }}</option>
      </select>
      <template v-if="!onlyProvince">
        <select
          :style="{width: `${31}%`}"
          @change="getAreas"
          v-model="currentCity"
          :disabled="disabled"
          :class="{'area-block': isBlock}">
          <option :value="placeholders.city">{{ placeholders.city }}</option>
          <option v-for="(item, index) in cities" :value="item">{{ item }}</option>
        </select>
        <select
          :style="{width: `${31}%`}"
          v-if="!hideArea && areas.length != 0"
          v-model="currentArea"
          :disabled="disabled"
          :class="{'area-block': isBlock}">
          <option :value="placeholders.area">{{ placeholders.area }}</option>
          <option v-for="(item, index) in areas" :value="item">{{ item }}</option>
        </select>
      </template>
    </template>
  </div>
</template>

<script>
import DISTRICTS from './districts'

const DEFAULT_CODE = 100000

export default {
  name: 'zz-areaPicker',
  props: {
    province: {type: [String, Number], default: ''},
    city: {type: [String, Number], default: ''},
    area: {type: [String, Number], default: ''},
    hideArea: {type: Boolean, default: false},
    onlyProvince: {type: Boolean, default: false},
    staticPlaceholder: {type: Boolean, default: false},
    placeholders: {
      type: Object,
      default () {
        return {
          province: '省',
          city: '市',
          area: '区'
        }
      }
    },
    disabled: {type: Boolean, default: false},
    addressHeader: {type: String, default: 'address-header'},
    addressContainer: {type: String, default: 'address-container'},
    isBlock: {type: Boolean, default: false},
    isBorder: {type: Boolean, default: true},
    optionData: {
      type: Object,
      dafault: function () {
        return {}
      }
    },
    resetPlace: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      provinces: [],
      cities: [],
      areas: [],
      currentProvince: this.determineType(this.province) || this.placeholders.province,
      currentCity: this.determineType(this.city) || this.placeholders.city,
      currentArea: this.determineType(this.area) || this.placeholders.area
    }
  },
  created () {
    this.provinces = this.getDistricts()
    this.cities = this.province !== '省' ? this.getDistricts(this.getAreaCode(this.determineType(this.province), '', 'province')) : []
    this.areas = this.city !== '市' ? this.determineValue(this.city, this.placeholders.city, this.province) : []
      // this.getDistricts(this.getAreaCode(this.determineType(this.city), this.area, 'area'))
  },
  watch: {
    currentProvince (vaule) {
      let data = this.setData(vaule)
      if (this.optionData) {
        data = {...this.optionData, ...data}
      }
      if (data.value === '省') {
        data.value = ''
      }
      this.$emit('province', data)
      if (this.onlyProvince) this.emit('selected')
    },
    currentCity (value) {
      let data = this.setData(value, this.currentProvince)
      if (this.optionData) {
        data = {...this.optionData, ...data}
      }
      if (data.value === '市') {
        data.value = ''
      }
      this.$emit('city', data)
      if (value !== this.placeholders.city && this.hideArea) this.emit('selected')
    },
    currentArea (value) {
      if (value !== this.placeholders.area) {
        let data = this.setData(value, this.currentProvince)
        if (this.optionData) {
          data = {...this.optionData, ...data}
        }
        if (data.value === '区') {
          data.value = ''
        }
        this.$emit('area', data)
      }
      if (value !== this.placeholders.area) this.emit('selected')
    },
    province () {
      this.currentProvince = this.province || this.placeholders.province
      this.cities = this.determineValue(this.currentProvince, this.placeholders.province)
    },
    city () {
      this.currentCity = this.city || this.placeholders.city
      this.areas = this.determineValue(this.currentCity, this.placeholders.city, this.currentProvince)
    },
    area () {
      this.currentArea = this.area || this.placeholders.area
    },
    resetPlace () {
      this.currentProvince = this.placeholders.province
      this.currentCity = this.placeholders.city
      this.currentArea = this.placeholders.area
    }
  },
  methods: {
    setData (value, check = '') {
      return {
        code: this.getAreaCode(value, check),
        value: value
      }
    },
    emit (name) {
      let data = {
        province: this.setData(this.currentProvince)
      }

      if (!this.onlyProvince) {
        this.$set(data, 'city', this.setData(this.currentCity))
      }

      if (!this.onlyProvince || this.hideArea) {
        this.$set(data, 'area', this.setData(this.currentArea))
      }

      this.$emit(name, data)
    },
    getCities () {
      this.currentCity = this.placeholders.city
      this.currentArea = this.placeholders.area
      this.cities = this.determineValue(this.currentProvince, this.placeholders.province)
      this.cleanList('areas')
      if (this.cities === null) {
        this.emit('selected')
      }
    },
    getAreas () {
      this.currentArea = this.placeholders.area
      this.areas = this.determineValue(this.currentCity, this.placeholders.city, this.currentProvince)
      if (this.areas === null) {
        this.emit('selected')
      }
    },
    getAreaCode (name, check = '', type = '') {
      for (let x in DISTRICTS) {
        for (let y in DISTRICTS[x]) {
          if (DISTRICTS[x][y].includes(name)) {
            if (type === 'province') {
              this.currentProvince = DISTRICTS[x][y]
            }
            if (type === 'area') {
              this.currentCity = DISTRICTS[x][y]
            }
            if (check.length > 0) {
              if (y.slice(0, 2) !== this.getAreaCode(check).slice(0, 2)) {
                continue
              } else {
                return y
              }
            } else {
              return y
            }
          }
        }
      }
    },
    getCodeValue (code) {
      for (let x in DISTRICTS) {
        for (let y in DISTRICTS[x]) {
          if (code === y) {
            return DISTRICTS[x][y]
          }
        }
      }
    },
    getDistricts (code = DEFAULT_CODE) {
      return DISTRICTS[code] || null
    },
    determineValue (currentValue, placeholderValue, check = '') {
      if (currentValue === placeholderValue) {
        return []
      } else {
        return this.getDistricts(this.getAreaCode(currentValue, check))
      }
    },
    determineType (value) {
      if (typeof value === 'number') {
        return this.getCodeValue(value)
      }
      return value
    },
    cleanList (name) {
      this[name] = []
    }
  }
}
</script>

<style lang="scss" scoped>
.address {
  box-sizing: border-box;
  select {
    height: 20px;
    color: #8b999a;
    border: none;
    appearance:none;
    -moz-appearance:none;
    -webkit-appearance:none;
    background: url(../../assets/img/select.jpg) no-repeat right center;
    cursor: pointer;
    padding-right: 30px;
    padding-left: 10px;
    @include ellipsis;
    option {
      font-weight: normal;
      display: block;
      white-space: pre;
      min-height: 1.2em;
      padding: 0 2px 1px;
    }
  }
  .area-block{
    border: 1px $color-line solid;
    border-radius: 3px;
    height: 30px;
    line-height: 30px;
    padding-left: 10px;
  }
}
.border{
  border: 1px $color-line solid;
  border-radius: 3px;
}
</style>
